package com.miage.itrading.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.miage.itrading.entites.RSSItem;
import com.miage.itrading.utils.ConnecteurBDD;
import com.miage.itrading.utils.Util;

public class RSSDao {
	
	private ArrayList<String>	RSSs;
	private ArrayList<String>	urls;
	private ArrayList<Date>		dates;
	private ArrayList<String>	titles;
	
	public RSSDao() {
		RSSs	= new ArrayList<String>();
		urls	= new ArrayList<String>();
		dates	= new ArrayList<Date>();
		titles	= new ArrayList<String>();
	}
	
	/**
	 * Fonctions utilisées par le client
	 * @throws SQLException 
	 */
	public List<RSSItem> getLastItems(int nb) throws SQLException {

		ResultSet result = ConnecteurBDD.executeQuery("SELECT * FROM rss_src ORDER BY date DESC LIMIT 0, " + Math.abs(nb));
		
		ArrayList<RSSItem> retour = new ArrayList<RSSItem>();
		
		while (result.next()) {
			retour.add(new RSSItem(result.getString("url_referente"), 
								   result.getString("url"), 
								   result.getString("titre"), 
								   Util.getDateBySQL(result.getTimestamp("date"))));
		}
		
		return retour;
	}
	
	/**
	 * Fonctions utilisées par le serveur 
	 */
	
	public void add(String rss, String url, String title, Date date) {		
		RSSs.add(rss.replaceAll("'", "''"));
		urls.add(url.replaceAll("'", "''"));
		titles.add(title.replaceAll("'", "''"));
		dates.add(date);
	}
	
	public void flush() throws SQLException {
		if (urls.size()>0) {
			String sqlOrder = "INSERT INTO rss_src (url_referente, url, titre, date) VALUES ";
			int i;
			for (i = 0; i<urls.size(); ++i) {
				sqlOrder = sqlOrder + "('" + RSSs.get(i) + "', '" + urls.get(i) + "', '" + titles.get(i) + "', '" + Util.getTimeStampByJavaDate(dates.get(i)) + "'), ";
			}
			sqlOrder = sqlOrder.substring(0, sqlOrder.length() - 2);
			
			// Flushes the buffer
			RSSs.clear();
			urls.clear();
			dates.clear();
			titles.clear();
			
			ConnecteurBDD.executeUpdate(sqlOrder);
		}
	}
	
	/**
	 * La date du plus récent article avec cette URL en référence
	 * 
	 * @param url
	 * @return
	 * @throws SQLException
	 */
	public Date getLastRecord(String urlReferente) throws SQLException {
		ResultSet result = ConnecteurBDD.executeQuery("SELECT date from rss_src " +
													  "WHERE url_referente = '" + urlReferente + "' " +
													  "ORDER BY date desc " +
													  "LIMIT 0, 1"); 
		
		if (result.next()) {
			return Util.getDateBySQL(result.getTimestamp("date"));
		}
		else {
			return null;
		}
	}
}
